import axios from 'axios'
import { THREE } from 'threebox-plugin'
import Constants from './constants'
import util from './util'

class BuildingManager {
  constructor(vueInstance) {
    this.map = vueInstance.map
    this.tb = vueInstance.threeBoxLayer.tb
    this.vueInstance = vueInstance
    this.buildingObjects = []
    this.init()
  }

  init () {
    // 添加外部楼层模型数据
    axios.get('./models/buildings.json').then(res => {
      const outerBuildingList = res.data
      outerBuildingList.forEach(building => {
        let options = {
          type: 'gltf',
          obj: `./models/江湾雅园/outer/${building.model}`,
          units: 'meters',
          rotation: { x: 0, y: 0, z: 180 },
          anchor: 'auto',
          modelType: 'building',
          name: building.name,
          bbox: false,
          ...building.properties
        }
        this.tb.loadObj(options, (model) => {
          model.setCoords(Constants.origin)
          model.name = name
          this.tb.add(model)
          this.buildingObjects.push(model)
        })
      })
    })
  }

  easeToBuilding() {
    let {buildingId, bearing} = this.vueInstance.$store.state.buildingOverview
    let buildingObject = this.buildingObjects.find(item => item.userData.buildingId === buildingId)
    this.flatternOthers()
    let center = util.max2lnglat({ x: buildingObject.center.x, y: buildingObject.center.y - 100 * Math.tan((30 * Math.PI) / 180) }, Constants.origin)
    this.map.easeTo({
      center,
      zoom: 18.5,
      bearing,
      pitch: 56,
      duration: 2000
    })
  }

  flatternOthers() {
    let {buildingId} = this.vueInstance.$store.state.buildingOverview
    this.buildingObjects.forEach( item => {
      if (item.userData.buildingId === buildingId) {
        return
      }
      util.flattern(item);
      item.removeTooltip();
      if (item.boundingBox) {
        item.boundingBox.visible = false;
      }
    })
  }

  extrustOthers() {
    let {buildingId} = this.vueInstance.$store.state.buildingOverview
    this.buildingObjects.forEach( item => {
      if (item.userData.buildingId === buildingId) {
        return
      }
      util.extrust(item);
    })
  }

  reset() {
    const cameraObj = {
      center: [120.5870808494, 31.2902111951],
      zoom: 17,
      bearing: -10.601,
      pitch: 56.5,
      duration: 2000
    }
    this.map.easeTo(cameraObj)
    // 地图样式恢复
    this.extrustOthers()
  }
}

export default BuildingManager